﻿using System;
using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Rpc.Abstractions;
using Rpc.Abstractions.CircuitBreaker;
using Rpc.Abstractions.Service;
using Rpc.Codec.MessagePack;
using Rpc.DynamicProxy;

namespace Rpc.Core
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddRpc(this IServiceCollection serviceCollection, Action<IRpcBuilder> builder)
        {
            serviceCollection.AddBase();
            var config = new RpcBuilder(serviceCollection);
            builder(config);
            serviceCollection.AddSingleton(config.RpcSettings);
            return serviceCollection;
        }

        public static IServiceCollection AddRpc(this IServiceCollection serviceCollection,
            IConfiguration configuration, Action<IRpcSampleBuilder> builder)
        {
            serviceCollection.AddBase();
            var config = new RpcSampleBuilder(serviceCollection, configuration);
            builder(config);
            serviceCollection.AddSingleton(config.RpcSettings);
            return serviceCollection;
        }
        public static ContainerBuilder AddRpc(this ContainerBuilder builder, IServiceCollection serviceCollection, IConfiguration configuration, Action<IRpcSampleBuilder> rpcbuilder)
        {
            serviceCollection.AddRpc(configuration, rpcbuilder);
            builder.Populate(serviceCollection);
            return builder;
        }
        private static void AddBase(this IServiceCollection serviceCollection)
        {
            serviceCollection.AddSingleton<IHostedService, ServiceBuilder>();
            serviceCollection.AddSingleton<IServiceFactory, ServiceFactory>();
            serviceCollection.AddSingleton<IScriptInjection, ScriptInjection>();
            serviceCollection.AddSingleton<ICodec, MessagePackCodec>();
        }
    }
}
